<?php

declare(strict_types=1);

namespace App\CustHub\Service;

use App\CustHub\Mapper\ChWordMapper;
use Mine\Abstracts\AbstractService;
use Mine\Exception\NormalStatusException;

class WordService extends AbstractService
{
    public $mapper;

    public function __construct(ChWordMapper $mapper)
    {
        $this->mapper = $mapper;
    }

    public function save(array $data): mixed
    {
        $data = $this->changeData($data);
        $data['sort'] = $this->mapper->model::query() -> max('sort') + 1;
        return $this->mapper->save($data);
    }

    public function update(mixed $id, array $data): bool
    {
        $data = $this->changeData($data);
        return $this->mapper->update($id, $data);
    }

    public function copy(array $params)
    {
        $id = $params['id'];
        $word = $this->mapper->first(['id' => $id]);
        if(empty($word)){
            throw new NormalStatusException('复制失败');
        }
        $word = $word->toArray();
        unset($word['created_at'], $word['updated_at'], $word['id']);
        $word['sort'] = $this->mapper->model::query() -> max('sort') + 1;
        return $this->mapper->save($word);
    }

    public function changeData(array $data)
    {
        $content = $data['content'];
        if(!is_array($content)){
            $content = json_decode($content, true);
        }
        $info = CommonService::formatMsgContent($content);
        $data['content'] = $info['content'];
        $data['msg_types'] = $info['msg_types'];
        return $data;
    }

}